import * as types from '../types'
import { getInTheaters, getDetail, getTop250, getComingSoon } from '@/services/m/'  // eslint-disable-line

export default {
  state: {
    list: [],
    total: 0,
    initing: true,
    detail: {
      title: '',
      img: '',
      directors: '',
      writers: '',
      casts: '',
      genres: '',
      countries: '',
      languages: '',
      pubdates: '',
      durations: '',
      aka: '',
      summary: ''
    }
  },

  mutations: {
    fetchSuccess (state, { subjects, total }) {
      if (subjects) {
        state.list = [...state.list, ...subjects]
        state.initing = false
        state.total = total
      }
    },

    [types.FETCH_DETAIL] (state, item) {
      state.initing = false
      state.detail.title = item.title
      state.detail.img = item.images.medium
      state.detail.directors = item.directors.map(u => u.name).join(' / ')
      state.detail.casts = item.casts.map(u => u.name).join(' / ')
      state.detail.genres = item.genres.join(' / ')
      state.detail.countries = item.countries.join(' / ')
      state.detail.pubdates = item.year
      state.detail.aka = item.aka.join(' / ')
      state.detail.summary = item.summary
    },

    [types.RESET_MOVIE_STATE] (state) {
      state.list = []
      state.total = 0
      state.initing = true
    }
  },

  actions: {
    [types.FETCH_IN_THEATERS] ({ state, commit }, payload) {
      let { start, count } = payload
      if (!start) {
        start = state.list.length
      }
      return new Promise((resolve, reject) => {
        getInTheaters(start, count)
          .then((data) => {
            commit('fetchSuccess', data)
            resolve()
          })
      })
    },

    [types.FETCH_TOP_250] ({ state, commit }, payload) {
      let { start, count } = payload
      if (!start) {
        start = state.list.length
      }
      return new Promise((resolve, reject) => {
        getTop250(start, count)
          .then((data) => {
            commit('fetchSuccess', data)
          })
      })
    },

    [types.FETCH_COMING_SOON] ({ state, commit }, payload) {
      let { start, count } = payload
      if (!start) {
        start = state.list.length
      }
      return new Promise((resolve, reject) => {
        getComingSoon(start, count)
          .then((data) => {
            commit('fetchSuccess', data)
          })
      })
    },

    [types.FETCH_DETAIL] ({ state, commit }, payload) {
      let { id } = payload
      getDetail(id)
        .then((data) => {
          commit(types.FETCH_DETAIL, data)
        })
    }
  }
}
